<template>
  <el-container>
    <el-aside width="250px" v-loading="loading">
      <el-container>
        <el-header>
          <el-input placeholder="输入关键字进行过滤" v-model="dictName" clearable></el-input>
        </el-header>
        <el-main class="nopadding">
          <el-tree ref="dictType" class="menu" node-key="id" :data="dictTypeList" :props="dictProps"
                   :highlight-current="true"
                   :expand-on-click-node="false" :filter-node-method="dictFilterNode" @node-click="dictNodeClick">
            <template #default="{node, data}">
							<span class="custom-tree-node">
								<span class="label">{{ data.dictName }}</span>
								<span class="code">{{ data.dictCode }}</span>
								<span class="do">
									<el-button-group>
										<el-button icon="el-icon-edit" size="small" @click.stop="handleUpdate(data)"></el-button>
										<el-button icon="el-icon-delete" size="small" @click.stop="handleDelete(data)"></el-button>
									</el-button-group>
								</span>
							</span>
            </template>
          </el-tree>
        </el-main>
        <el-footer style="height:51px;">
          <el-button type="primary" size="small" icon="el-icon-plus" style="width: 100%;" @click="handleAdd">字典分类
          </el-button>
        </el-footer>
      </el-container>
    </el-aside>

    <el-dialog destroy-on-close append-to-body width="900px" :title="title" v-model="open"
               :close-on-click-modal="false" @closed="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="字典标识" prop="dictCode">
              <el-input v-model="form.dictCode" clearable placeholder="字典标识"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典名称" prop="dictName">
              <el-input v-model="form.dictName" clearable placeholder="字典名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="字典类型" prop="dictType">
              <el-radio-group v-model="form.dictType">
                <!--                <el-radio-button label="USER_DICT">用户字典</el-radio-button>-->
                <el-radio-button label="SYSTEM_DICT">系统字典</el-radio-button>
                <el-radio-button label="PLATFORM_DICT">平台字典</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否有效" prop="status">
              <el-switch v-model="form.status" :active-value="true" :inactive-value="false"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" clearable type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" :loading="saveing" @click="submitForm">保 存</el-button>
      </template>
    </el-dialog>

    <el-container class="is-vertical">
      <el-header>
        <div class="left-panel">
          <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              @click="handleAdd2"
          >新增
          </el-button>
          <el-button
              type="success"
              plain
              icon="el-icon-edit"
              :disabled="single"
              @click="handleUpdate2"
          >修改
          </el-button>
          <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              :disabled="multiple"
              @click="handleDelete2"
          >删除
          </el-button>
        </div>
        <div class="right-panel">
          <jcx-table-bar :search="false" @queryTable="getList2" :columns="columns"></jcx-table-bar>
        </div>
      </el-header>
      <el-main class="nopadding">
        <el-table ref="table" style="width: 100%" v-loading="loading2" :data="dictDataList" row-key="dataId"
                  @selection-change="handleSelectionChange"
                  :stripe="config.stripe" :border="config.border" :size="config.size">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column label="字典标签" align="center" prop="dataLabel" v-if="columns[0].visible"></el-table-column>
          <el-table-column label="字典键值" align="center" prop="dataValue" v-if="columns[1].visible"></el-table-column>
          <el-table-column label="备注" align="center" prop="remark" v-if="columns[2].visible"></el-table-column>
          <el-table-column label="是否默认" align="center" prop="isDefault" v-if="columns[3].visible">
            <template #default="props">
              <el-tag v-if="props.row.isDefault" type="primary">是</el-tag>
              <el-tag v-if="!props.row.isDefault" type="warning">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status" v-if="columns[4].visible">
            <template #default="props">
              <el-tag v-if="props.row.status" type="success">启用</el-tag>
              <el-tag v-if="!props.row.status" type="danger">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[5].visible"></el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="props">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate2(props.row)"
              >修改
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete2(props.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <jcx-page
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList2"
        ></jcx-page>
      </el-main>
    </el-container>

    <el-dialog destroy-on-close append-to-body width="900px" :title="title2" v-model="open2"
               :close-on-click-modal="false" @closed="cancel2">
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="字典类型" prop="dictId">
              <el-select style="width: 100%;" v-model="form2.dictId" placeholder="请选择字典类型"
                         @change="dictIdChange">
                <el-option
                    v-for="dict in formDictTypeList"
                    :key="dict.dictId"
                    :label="dict.dictName"
                    :value="dict.dictId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form2.sort" :precision="2" :min="1" :step="0.01"
                               controls-position="right"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="字典标签" prop="dataLabel">
              <el-input v-model="form2.dataLabel" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典键值" prop="dataValue">
              <el-input v-model="form2.dataValue" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否默认" prop="isDefault">
              <el-switch v-model="form2.isDefault" :active-value="true" :inactive-value="false"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否有效" prop="status">
              <el-switch v-model="form2.status" :active-value="true" :inactive-value="false"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="样式属性" prop="cssClass">
              <el-input v-model="form2.cssClass" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="回显样式" prop="listClass">
              <el-select v-model="form2.listClass">
                <el-option
                    v-for="item in listClassOptions"
                    :key="item.value"
                    :label="item.label + '(' + item.value + ')'"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form2.remark" clearable type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="cancel2">取 消</el-button>
        <el-button type="primary" :loading="saveing2" @click="submitForm2">保 存</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>

<script>
export default {
  name: "Dict",
  data() {
    return {
      // 遮罩层
      loading: true,
      loading2: true,
      // 保存遮罩层
      saveing: false,
      saveing2: false,
      // 字典名
      dictName: '',
      // 字典类型列表数据
      dictTypeList: [],
      formDictTypeList: [],
      // 字典Props
      dictProps: {
        label: 'dictName'
      },
      // 弹窗标题
      title: '',
      // 是否显示弹窗
      open: false,
      // 表单对象
      form: {},
      rules: {
        dictCode: [
          {required: true, message: '请输入字典标识', trigger: 'blur'}
        ],
        dictName: [
          {required: true, message: '请输入字典名称', trigger: 'blur'}
        ],
        dictType: [
          {required: true, message: '请选择字典类型', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择是否有效', trigger: 'blur'}
        ],
      },
      // 弹窗标题
      title2: '',
      // 是否显示弹窗
      open2: false,
      // 分页总条数
      total: 0,
      // 查询参数
      queryParams: {
        dictCode: undefined,
        pageNum: 1,
        pageSize: 10
      },
      // 字典值列表
      dictDataList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 表格配置
      config: {
        // 表格大小
        size: "default",
        // 表格边框
        border: true,
        // 表格斑马图纹
        stripe: true
      },
      form2: {},
      rules2: {
        dictId: [
          {required: true, message: '请输入字典类型ID', trigger: 'blur'}
        ],
        dictCode: [
          {required: true, message: '请输入字典类型标识', trigger: 'blur'}
        ],
        dataLabel: [
          {required: true, message: '请输入字典标签', trigger: 'blur'}
        ],
        dataValue: [
          {required: true, message: '请输入字典键值', trigger: 'blur'}
        ],
        isDefault: [
          {required: true, message: '请选择是否默认', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择是否启用', trigger: 'blur'}
        ],
      },
      // 数据标签回显样式
      listClassOptions: [
        {
          value: "default",
          label: "默认"
        },
        {
          value: "primary",
          label: "主要"
        },
        {
          value: "success",
          label: "成功"
        },
        {
          value: "info",
          label: "信息"
        },
        {
          value: "warning",
          label: "警告"
        },
        {
          value: "danger",
          label: "危险"
        }
      ],
      columns: [
        {key: 0, label: `字典标签`, visible: true},
        {key: 1, label: `字典键值`, visible: true},
        {key: 2, label: `备注`, visible: true},
        {key: 3, label: `是否默认`, visible: true},
        {key: 4, label: `状态`, visible: true},
        {key: 5, label: `创建时间`, visible: false},
      ],
    };
  },
  watch: {
    dictName(value) {
      this.$refs.dictType.filter(value);
    }
  },
  created() {
    this.getList();
    this.getList2();
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true
      this.$API.dict.pageListDictType.get({status: true}).then(response => {
        if (response.status) {
          this.formDictTypeList = response.data.records
        } else {
          this.$message.warning(response.msg);
        }
      })
      this.$API.dict.pageListDictType.get(null).then(response => {
        if (response.status) {
          this.dictTypeList = response.data.records
        } else {
          this.$message.warning(response.msg);
        }
        this.loading = false;
      })
    },
    dictFilterNode(value, data) {
      if (!value) return true;
      let targetText = data.dictName + data.dictCode;
      return targetText.indexOf(value) !== -1;
    },
    dictNodeClick(data) {
      this.queryParams.dictCode = data.dictCode
      this.getList2()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加字典类型";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(`确定删除选中的 ${row.dictName} 字典类型吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        this.$API.dict.delDictTypes.delete([row.dictId]).then(response => {
          if (response.status) {
            this.$message.success(response.msg);
            this.getList();
          } else {
            this.$alert(response.msg, "提示", {type: 'error'});
          }
        });
      }).catch(() => {
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.$API.dict.getDictTypeById.get(row.dictId).then(response => {
        if (response.status) {
          this.form = response.data;
          this.open = true;
          this.title = "修改字典类型";
        } else {
          this.$message.warning(response.msg);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveing = true;
          // 如果 ID 存在就是更新
          if (this.form.dictId) {
            this.$API.dict.editDictType.put(this.form).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          } else {
            // 不存在就是新增
            this.$API.dict.addDictType.post(this.form).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          }
        }
      });
    },
    reset() {
      this.form = {
        dictId: "",
        dictCode: "",
        dictName: "",
        dictType: "USER_DICT",
        status: true,
        remark: "",
      };
      this.$nextTick(() => {
        if (this.$refs['form']) {
          this.$refs['form'].clearValidate();
          this.$refs['form'].resetFields();
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.saveing = false;
      this.reset();
    },

    dictIdChange(dictId) {
      for (let i = 0; i < this.formDictTypeList.length; i++) {
        if (this.formDictTypeList[i].dictId === dictId) {
          this.form2.dictCode = this.formDictTypeList[i].dictCode
        }
      }
    },
    cancel2() {
      this.open2 = false;
      this.saveing2 = false;
      this.reset2();
    },
    /** 查询列表 */
    getList2() {
      this.loading2 = true
      this.$API.dict.pageListDictData.get(this.queryParams).then(response => {
        if (response.status) {
          this.dictDataList = response.data.records
          this.total = response.data.total
        } else {
          this.$message.warning(response.msg);
        }
        this.loading2 = false;
      })
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dataId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    reset2() {
      this.form2 = {
        dataId: "",
        dictId: "",
        dictCode: "",
        dataLabel: "",
        dataValue: "",
        cssClass: "",
        listClass: "",
        isDefault: false,
        sort: "",
        status: true,
        remark: ""
      };
      this.$nextTick(() => {
        if (this.$refs['form2']) {
          this.$refs['form2'].clearValidate();
          this.$refs['form2'].resetFields();
        }
      });
    },
    handleAdd2() {
      this.reset2();
      this.open2 = true;
      this.title2 = "添加字典值";
    },
    handleDelete2(row) {
      const dataIds = row.dataId ? [row.dataId] : this.ids;
      this.$confirm(`确定删除选中的 ${dataIds.length} 项吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        this.$API.dict.delDictDatas.delete(dataIds).then(response => {
          if (response.status) {
            this.$message.success(response.msg);
            this.getList2();
          } else {
            this.$alert(response.msg, "提示", {type: 'error'});
          }
        });
      }).catch(() => {
      })
    },
    handleUpdate2(row) {
      this.reset2();
      const dataId = row.dataId || this.ids
      this.$API.dict.getDictDataById.get(dataId).then(response => {
        if (response.status) {
          this.form2 = response.data;
          this.open2 = true;
          this.title2 = "修改字典值";
        } else {
          this.$message.warning(response.msg);
        }
      });
    },
    /** 提交按钮 */
    submitForm2() {
      this.$refs["form2"].validate(valid => {
        this.saveing2 = true;
        if (valid) {
          // 如果 ID 存在就是更新
          if (this.form2.dataId) {
            this.$API.dict.editDictData.put(this.form2).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing2 = false;
                this.open2 = false;
                this.getList2();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing2 = false;
              }
            });
          } else {
            // 不存在就是新增
            this.$API.dict.addDictData.post(this.form2).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing2 = false;
                this.open2 = false;
                this.getList2();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing2 = false;
              }
            });
          }
        }
      })
    },
  }
}
</script>

<style scoped>
.menu:deep(.el-tree-node__label) {
  display: flex;
  flex: 1;
  height: 100%;
}

.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 24px;
  height: 100%;
}

.custom-tree-node .code {
  font-size: 12px;
  color: #999;
}

.custom-tree-node .do {
  display: none;
}

.custom-tree-node:hover .code {
  display: none;
}

.custom-tree-node:hover .do {
  display: inline-block;
}
</style>

